/**
 * PermissionManager - 权限管理组件
 * 
 * 该文件用于管理应用的运行时权限请求，特别是蓝牙相关权限
 * 使用 Accompanist Permissions 库简化权限处理流程
 * 
 * 功能：
 * - 检查和请求蓝牙相关权限
 * - 处理不同 Android 版本的权限差异
 * - 提供权限状态回调
 * 
 * 权限列表：
 * - BLUETOOTH_SCAN: 扫描蓝牙设备 (Android 12+)
 * - BLUETOOTH_CONNECT: 连接蓝牙设备 (Android 12+)
 * - ACCESS_FINE_LOCATION: 位置权限 (所有版本)
 * - BLUETOOTH: 蓝牙基础权限 (Android 12以下)
 * - BLUETOOTH_ADMIN: 蓝牙管理权限 (Android 12以下)
 */

package com.example.brain_wave.ui.components

import android.Manifest
import android.os.Build
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import com.google.accompanist.permissions.*

/**
 * 获取需要请求的蓝牙权限列表
 * 根据 Android 版本返回不同的权限组合
 */
@OptIn(ExperimentalPermissionsApi::class)
fun getBluetoothPermissions(): List<String> {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        // Android 12+ 需要新的蓝牙权限
        listOf(
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    } else {
        // Android 12以下使用传统蓝牙权限
        listOf(
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    }
}

/**
 * 蓝牙权限管理组件
 * 
 * @param onPermissionsResult 权限请求结果回调，true表示所有权限已授予
 * @param content 权限授予后显示的内容
 */
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun BluetoothPermissionManager(
    onPermissionsResult: (Boolean) -> Unit,
    content: @Composable () -> Unit
) {
    val context = LocalContext.current
    val permissions = getBluetoothPermissions()
    
    val multiplePermissionsState = rememberMultiplePermissionsState(
        permissions = permissions
    ) { permissionsMap ->
        // 检查所有权限是否都已授予
        val allGranted = permissionsMap.values.all { it }
        onPermissionsResult(allGranted)
    }
    
    LaunchedEffect(multiplePermissionsState.allPermissionsGranted) {
        onPermissionsResult(multiplePermissionsState.allPermissionsGranted)
    }
    
    when {
        multiplePermissionsState.allPermissionsGranted -> {
            // 所有权限已授予，显示主要内容
            content()
        }
        multiplePermissionsState.shouldShowRationale -> {
            // 需要显示权限说明
            PermissionRationaleDialog(
                onRequestPermissions = {
                    multiplePermissionsState.launchMultiplePermissionRequest()
                },
                onDismiss = {
                    onPermissionsResult(false)
                }
            )
        }
        else -> {
            // 首次请求权限或用户拒绝了权限
            PermissionRequestDialog(
                onRequestPermissions = {
                    multiplePermissionsState.launchMultiplePermissionRequest()
                },
                onDismiss = {
                    onPermissionsResult(false)
                }
            )
        }
    }
}

/**
 * 权限说明对话框
 * 当用户之前拒绝过权限时显示
 */
@Composable
private fun PermissionRationaleDialog(
    onRequestPermissions: () -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text("需要蓝牙权限")
        },
        text = {
            Text(
                text = "为了连接和使用蓝牙设备，应用需要以下权限：\n\n" +
                        "• 蓝牙扫描权限 - 搜索附近的蓝牙设备\n" +
                        "• 蓝牙连接权限 - 连接到蓝牙设备\n" +
                        "• 位置权限 - 蓝牙扫描需要位置权限\n\n" +
                        "请点击\"授予权限\"来启用这些功能。",
                textAlign = TextAlign.Start
            )
        },
        confirmButton = {
            TextButton(onClick = onRequestPermissions) {
                Text("授予权限")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

/**
 * 权限请求对话框
 * 首次请求权限时显示
 */
@Composable
private fun PermissionRequestDialog(
    onRequestPermissions: () -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text("蓝牙权限请求")
        },
        text = {
            Text(
                text = "应用需要蓝牙和位置权限来连接脑波设备。\n\n" +
                        "这些权限用于：\n" +
                        "• 搜索和连接NeuroSky设备\n" +
                        "• 接收脑波数据\n" +
                        "• 提供实时数据分析\n\n" +
                        "请在接下来的系统对话框中选择\"允许\"。",
                textAlign = TextAlign.Start
            )
        },
        confirmButton = {
            TextButton(onClick = onRequestPermissions) {
                Text("请求权限")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("稍后再说")
            }
        }
    )
}

/**
 * 权限被拒绝时的提示组件
 */
@Composable
fun PermissionDeniedContent(
    onRetryPermissions: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Icon(
            imageVector = Icons.Default.Info,
            contentDescription = "权限警告",
            modifier = Modifier.size(64.dp),
            tint = MaterialTheme.colorScheme.error
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        Text(
            text = "需要蓝牙权限",
            style = MaterialTheme.typography.headlineSmall,
            textAlign = TextAlign.Center
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        Text(
            text = "应用需要蓝牙和位置权限才能连接脑波设备。\n请在设置中手动授予权限，或点击下方按钮重新请求。",
            style = MaterialTheme.typography.bodyMedium,
            textAlign = TextAlign.Center,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        
        Spacer(modifier = Modifier.height(24.dp))
        
        Button(
            onClick = onRetryPermissions,
            modifier = Modifier.fillMaxWidth(0.6f)
        ) {
            Text("重新请求权限")
        }
    }
}